package com.sanjin.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sanjin.mall.common.constant.ProductConstant;
import com.sanjin.mall.product.entity.AttrAttrgroupRelationEntity;
import com.sanjin.mall.product.entity.AttrGroupEntity;
import com.sanjin.mall.product.entity.CategoryEntity;
import com.sanjin.mall.product.service.AttrAttrgroupRelationService;
import com.sanjin.mall.product.service.AttrGroupService;
import com.sanjin.mall.product.service.CategoryService;
import com.sanjin.mall.product.vo.AttrVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sanjin.mall.common.utils.PageUtils;
import com.sanjin.mall.common.utils.Query;

import com.sanjin.mall.product.dao.AttrDao;
import com.sanjin.mall.product.entity.AttrEntity;
import com.sanjin.mall.product.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService relationService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    AttrGroupService attrGroupService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrVo(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        //TODO 基本属性才保存relation
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()
                && attr.getAttrGroupId() != null) {
            relationService.saveByattrVo(attr);
        }
    }

    /**
     * 获取基本属性 根据 key 和 catelogId
     * @param params
     * @param catelogId
     * @return
     */
    @Override
    public PageUtils getAttrPageByType(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }

        if (attrType.equals("base")) { //判断是基本属性还是销售属性
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        } else {
            wrapper.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotEmpty(key)) {
            wrapper.like("attr_name", key).or().eq("attr_id", key);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        List<AttrVo> voList = page.getRecords().stream().map((x) -> {
            AttrVo attrVo = new AttrVo();
            BeanUtils.copyProperties(x, attrVo);

            //TODO 只有基本属性才有分组
            if ("base".equalsIgnoreCase(attrType)){
                Long attrId = x.getAttrId();
                AttrAttrgroupRelationEntity rel = relationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .eq("attr_id", attrId));
                if (rel != null) {
                    Long attrGroupId = rel.getAttrGroupId();
                    String groupName = attrGroupService.getOne(new QueryWrapper<AttrGroupEntity>()
                            .eq("attr_group_id", attrGroupId)).getAttrGroupName();
                    attrVo.setGroupName(groupName);
                }
            }

            Long catId = x.getCatelogId();
            CategoryEntity category = categoryService.getOne(new QueryWrapper<CategoryEntity>()
                    .eq("cat_id", catId));
            if (category != null) {
                String catelogName = category.getName();
                attrVo.setCatelogName(catelogName);
            }
            return attrVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(voList);
        return pageUtils;


    }

    @Override
    public void updateByAttrVo(AttrVo attrVo) {
        AttrEntity attr = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attr);
        this.updateById(attr);
        if (attrVo.getAttrType().intValue() == ProductConstant.AttrEnum
                .ATTR_TYPE_SALE.getCode()) {
            return;
        }
        //1.修改分组关联
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

        relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        relationEntity.setAttrId(attr.getAttrId());
        if (attrVo.getAttrGroupId() == null) {
            relationService.remove(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            return;
        }
        //判断饰新增还是修改
        BaseMapper<AttrAttrgroupRelationEntity> relationDao;
        relationDao = relationService.getBaseMapper();
        Long count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        if (count > 0) {//修改
            relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
        } else {//新增
            relationDao.insert(relationEntity);
        }
    }

    /**
     * 通过group来获取对应的attr
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrgroupId) {
        List<AttrAttrgroupRelationEntity> list = relationService.list(new QueryWrapper<AttrAttrgroupRelationEntity>()
                .eq("attr_group_id", attrgroupId));
        List<Long> attrIds = list.stream().map((x) -> x.getAttrId())
                .collect(Collectors.toList());
        if (attrIds == null || attrIds.size() == 0) return null;
        return this.listByIds(attrIds);
    }

    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        String key = (String) params.get("key");
        params.put("attrGroupId", attrgroupId);
        ArrayList<AttrEntity> list = baseMapper.getNoRelAttrByIdAndLike(params);
        IPage<AttrEntity> page = new Query<AttrEntity>().getPage(params);
        page.setTotal(list.size());
        page.setRecords(list);
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setOWNList(list);
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("search_type", 1).in("attr_id", attrIds);
        List<AttrEntity> attrEntities = baseMapper.selectList(wrapper);
        List<Long> searchAttrIds = attrEntities.stream().map(searchAttr -> searchAttr.getAttrId()).collect(Collectors.toList());
        return searchAttrIds;
    }

}